package edu.drexel.info636.assignments.models;

import java.util.ArrayList;
import java.util.Arrays;

import lombok.Getter;

import com.google.common.collect.Iterables;

/**
 * A single item (i.e. set of numbers) within a record.
 * 
 * @author Chase Miller
 *
 */
public class Record {

    @Getter
    private ArrayList<Double> numberSet;
    private static String SEPARATOR = ", ";

    /**
     * Creates a new instance of the object.
     */
    public Record() {
	this.numberSet = new ArrayList<Double>();
    }

    /**
     * Creates a new instance of the object.
     * 
     * @param numberSet
     *            - a set of numbers to be used in this record.
     */
    public Record(ArrayList<Double> numberSet) {
	this.numberSet = numberSet;
    }

    /**
     * Creates a new instance of the object using the provided string.
     * 
     * @param line
     */
    public Record(String line) {
	this();
	this.parseString(line);
    }

    /**
     * Parses the provided string.
     * 
     * @param line
     */
    private void parseString(String line) {
	ArrayList<String> itemsAsStrings = new ArrayList<String>(Arrays.asList(line.split(SEPARATOR)));

	for (String next : itemsAsStrings) {
	    try {
		Double nextDouble = new Double(next);
		this.numberSet.add(nextDouble);
	    } catch (NumberFormatException e) {
		// Ignore numbers that can't be parsed.
	    }
	}
    }

    /**
     * Adds a number to this record.
     * 
     * @param numberToAdd
     *            - the number to add.
     */
    public void addNumber(Double numberToAdd) {
	this.numberSet.add(numberToAdd);
    }

    /**
     * Returns this record as a string, separated by the build in SEPARATOR.
     */
    public String toString() {
	StringBuilder stringToReturn = new StringBuilder();

	synchronized (this.numberSet) {
	    if (!this.numberSet.isEmpty()) {
		Double lastObject = Iterables.getLast(this.numberSet);
		for (Double next : this.numberSet) {
		    stringToReturn.append(next);
		    if (lastObject != next) {
			stringToReturn.append(SEPARATOR);
		    }
		}
	    }
	}

	return stringToReturn.toString();
    }

    /**
     * Answers with the max numbers that are to be recorded in a record.
     * 
     * @return
     */
    public static int getMaxNumberssInRecord() {
	return 2;
    }
}
